package com.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.system.mapper.UsersMapper;
import com.system.pojo.Users;
import com.system.service.UsersService;
import com.system.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("loginUserService")
public class UsersServiceImpl implements UsersService {
    JSONUtil jsonUtil = new JSONUtil();
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public List<Users> select(Users users) {
        return usersMapper.select(users);
    }

    @Override
    public String insert(Users loginUser) {
        return jsonUtil.toJson("0", usersMapper.insert(loginUser), "");
    }

    @Override
    public String update(Users loginUser) {
        return jsonUtil.toJson("0", usersMapper.update(loginUser), "");
    }

    @Override
    public String delete(String id) {
        return jsonUtil.toJson("0", usersMapper.delete(id), "");
    }

    @Override
    public String selectUsersShuttle() {
        List<Users> userss = usersMapper.select(null);
        JSONArray userarr = new JSONArray();
        for (int i = 0; i < userss.size(); i++) {
            JSONObject userobj = new JSONObject();
            userobj.put("value", userss.get(i).getId());
            userobj.put("title", userss.get(i).getName());
            userobj.put("code", userss.get(i).getRole());
            userarr.add(userobj);
        }
        return userarr.toJSONString();
    }

    @Override
    public String updateUsersRole(List<Users> usersList) {
        if (usersList.get(0).getId() == "0" || usersList.get(0).getId().equals("0")) {
            System.out.println("清空角色ID为" + usersList.get(0).getRole() + "的用户");
            return jsonUtil.toJson("0", usersMapper.updateRolesNull(usersList.get(0).getRole()), "修改成功");
        }
        for (int i = 0; i < usersList.size(); i++) {
            System.out.println("修改ID为" + usersList.get(i).getId() + "的角色ID为" + usersList.get(i).getRole());
            usersMapper.update(usersList.get(i));
        }
        return jsonUtil.toJson("0", "1", "修改成功");
    }

    public UsersMapper getLoginUserMapper() {
        return usersMapper;
    }

    public void setLoginUserMapper(UsersMapper userMapper) {
        this.usersMapper = userMapper;
    }
}
